/**
Company: Sarkar software technologys
WebSite: http://www.sarkar.cn
Author: yeganaaa
Date : 5/19/18
Time: 12:05 AM
 */

package Cn.Sarkar.Configuration

import com.google.gson.GsonBuilder
import java.io.File
import kotlin.reflect.KClass

/**
 * تەڭشەك ھۆججىتى ھاسىللاش فۇنكىسىيەسى،
 * يەنى مەلۇم بىر مۇندەرىجىگە تىز سۈرئەتتە
 * json
 * شەكلىدە تەڭشەك ھۆججىتى قۇرۇشقا بولىدۇ
 */
fun <T: Any> makeConfig(configFilePath: String, type: KClass<T>, configObjectConstructor: () -> T): T {
    val gson = GsonBuilder().setPrettyPrinting().create()

    var Config = configObjectConstructor()

    val jsonConfigFile = File(configFilePath)
    if (!jsonConfigFile.exists()) {
        jsonConfigFile.parentFile.apply {
            if (!this.exists()) {
                this.mkdirs()
            }
        }
        jsonConfigFile.writeText(gson.toJson(Config))
    }

    Config = try {
        gson.fromJson(jsonConfigFile.readText(), type.java)
    } catch (exception: Exception) {
        exception.printStackTrace()

        jsonConfigFile.delete()
        makeConfig(configFilePath, type, configObjectConstructor)
    }

    return Config
}